package constellation.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {
    /*
@des : 获取网络数据的函数
@params : path : 网址
return
返回或得到的json数据
*/
public static String getJsonByNetwork(String path){
    String json = "";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        1创建网络地址对象
    try {
        URL url = new URL(path);
//            2.获取网络连接对象
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();  //开始连接
//            3.获取服务器返回的数据
        InputStream is = conn.getInputStream();
//            4.读取流当中的数据
        int hasRead = 0;
        byte[]buf = new byte[1024];
        while (true){
            hasRead = is.read(buf);
            if (hasRead == -1) {
                break;
            }
            baos.write(buf,0,hasRead);
        }
        is.close();
        json = baos.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}
}
